package cliente;

import cliente.auxiliar.*;

import cliente.gui.Login;
import cliente.gui.MyTwitter;
import cliente.gui.Register;
import cliente.gui.Erro;
import java.net.Socket;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author A8
 */
public class Cliente {

    private static String mainHost = "localhost";
    private static int mainPort = 7000;
    public static String tipoLiga = "TCP";

    public static void main(String args[]) {

        String host;
        int tenta = 0;
        Envia send = null;
        GereOperacoes gestor = new GereOperacoes();

        if (args.length == 0) {
            //host="193.136.206.103";
            host = "localhost";
        } else {
            host = args[0];
        }

        Login log = new Login(gestor);
        arrancaLigacao(gestor, log, tenta);
    }

    public static void arrancaLigacao(GereOperacoes gestor, Login log, int tentativas) {

        try {
            Socket sock_tcp = new Socket(mainHost, mainPort);
            System.out.println("Passei a parte de criar Socket!");

            Conexao ligacao = new Conexao(sock_tcp, mainHost, mainPort);
            gestor.setConexao(ligacao);

            Envia send = new Envia(ligacao, gestor);
            Recebe rec = new Recebe(ligacao, gestor);
            if (gestor.getMyTwi() == null) {
                gestor.setMyTwi(new MyTwitter("", gestor));
            }
            gestor.setEnvia(send);

            if (gestor.getRegister() == null) {
                gestor.setRegister(new Register(gestor));
            }
            gestor.setLogin(log);
            gestor.setRecebe(rec);
            log.setVisible(true);

            send.start();
            rec.start();


        } catch (Exception ex) {

            System.out.println("Antes:" + System.currentTimeMillis());
            dorme(5000);
            System.out.println("Depois:" + System.currentTimeMillis());

            System.out.println("[ERRO]HOST:\n" + ex.getMessage());
            Conexao falha = new Conexao();
            gestor.setConexao(falha);
            log.setVisible(true);
            tentativas++;

            if (tentativas > 20) {
                new Erro("Conexao", "Incapaz de ligar ao servidor!Desligar");
                dorme(10000);
                gestor.getConexao().setEstado("Desligado");
                System.exit(0);
            } else {
                arrancaLigacao(gestor, log, tentativas);
            }
        }
    }

    public static synchronized void dorme(int tempo) {

        try {
            Thread.sleep(tempo);
        } catch (InterruptedException ex0) {
            System.out.println("[Erro]:" + ex0.getMessage());
        }
    }
}
